package com.ruoyi.web.controller.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.constant.PingjiaContants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BsJingqu;
import com.ruoyi.system.domain.BsOrderDetails;
import com.ruoyi.system.domain.BsOrderInfo;
import com.ruoyi.system.domain.BsPingjia;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package: com.ruoyi.web.controller.biz
 * @Author: HanWL
 * @CreateTime: 2023-10-27 13:55
 * @Version: 1.0
 **/
@RestController
@Api(tags = "评价管理接口")
@RequestMapping("/bs/pingjia")
public class BsPingjiaController extends BaseController {

    @Resource
    private BsOrderInfoService bsOrderInfoService;
    @Resource
    private BsPingjiaService bsPingjiaService;
    @Resource
    private BsJingquService bsJingquService;
    @Resource
    private BsOrderDetailsService bsOrderDetailsService;
    @Resource
    private BsMenpiaoNumService bsMenpiaoNumService;
    @Resource
    private ISysUserService userService;

    @ApiOperation("评价分页(所有评价)")
    @GetMapping("allPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "审核状态(0待审核，1通过，2不通过)"),
            @ApiImplicitParam(name = "startTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "jingquName", value = "景区名称"),
            @ApiImplicitParam(name = "pageNum", value = "分页参数：第几页"),
            @ApiImplicitParam(name = "pageSize", value = "分页参数：每页条数"),
    })
    public TableDataInfo<?> allPage(Integer pingjiaStatus, String jingquName, String startTime, String endTime){
        LambdaQueryWrapper<BsPingjia> lqw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNull(pingjiaStatus)){
            lqw.eq(BsPingjia::getPingjiaStatus,pingjiaStatus);
        }
        if (StringUtils.isNotEmpty(jingquName)){
            List<BsJingqu> jingquList = bsJingquService.list(new LambdaQueryWrapper<BsJingqu>().like(BsJingqu::getJingquName, jingquName));
            if (StringUtils.isNotEmpty(jingquList)){
                lqw.in(BsPingjia::getJingquId,jingquList.stream().map(BsJingqu::getJingquId).collect(Collectors.toList()));
            }
        }
        if (StringUtils.isNotEmpty(startTime)){
            lqw.gt(BsPingjia::getCreateTime, startTime);
        }
        if (StringUtils.isNotNull(endTime)){
            lqw.lt(BsPingjia::getCreateTime, endTime);
        }
        startPage();
        List<BsPingjia> list = bsPingjiaService.list(lqw);
        TableDataInfo<BsPingjia> dataTable = getDataTable(list);
        // 设置此订单的门票种类
        list.forEach(x -> {
            StringBuilder sb = new StringBuilder();
            List<BsOrderDetails> orderDetailsList = bsOrderDetailsService.list(new LambdaQueryWrapper<BsOrderDetails>().eq(BsOrderDetails::getOrderId, x.getOrderId()));
            for (BsOrderDetails bsOrderDetails : orderDetailsList) {
                sb.append(bsMenpiaoNumService.getCategoryByNumId(bsOrderDetails.getMenpiaoNumId()).getMenpiaoName());
                sb.append(",");
            }
            x.setMenpiaoCategory(sb.toString());
        });
        dataTable.setRows(list);
        return dataTable;
    }

    @ApiOperation("根据景区ID,获取景区的所有审核通过的评价")
    @GetMapping("getPingjiaByJingquId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jingquId", value = "景区ID"),
            @ApiImplicitParam(name = "pageNum", value = "分页参数：第几页"),
            @ApiImplicitParam(name = "pageSize", value = "分页参数：每页条数"),
            @ApiImplicitParam(name = "type", value = "0-全部，1好评，2有图")
    })
    public TableDataInfo<?> getPingjiaByJingquId(Long jingquId,Integer type){
        LambdaQueryWrapper<BsPingjia> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BsPingjia::getJingquId, jingquId);
        lqw.eq(BsPingjia::getPingjiaStatus, PingjiaContants.EXAMINE_YES);
        if (type == 1){
            lqw.ge(BsPingjia::getPingjiaScore,3);
        }
        if (type == 2){
            lqw.isNotNull(BsPingjia::getPingjiaPictureUrl);
        }
        startPage();
        List<BsPingjia> list = bsPingjiaService.list(lqw);
        TableDataInfo<BsPingjia> dataTable = getDataTable(list);
        list.forEach(x -> {
            SysUser user = userService.getById(x.getUserId());
            x.setAvatar(user.getAvatar());
            x.setPhoneNumber(user.getNickName());
        });
        dataTable.setRows(list);
        return dataTable;
    }

    @ApiOperation("根据景区ID，获取景区的评价好评率等信息")
    @GetMapping("getPingjiaInfoByJingquId/{jingquId}")
    public AjaxResult<?> getPingjiaInfoByJingquId(@PathVariable Long jingquId){
        Map<String,Object> map = new HashMap<>();
        LambdaQueryWrapper<BsPingjia> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BsPingjia::getJingquId, jingquId);
        lqw.eq(BsPingjia::getPingjiaStatus, PingjiaContants.EXAMINE_YES);
        List<BsPingjia> list = bsPingjiaService.list(lqw);
        List<BsPingjia> goodPingjiaList = list.stream().filter(x -> x.getPingjiaScore() > 3).collect(Collectors.toList());
        // 好评率
        map.put("goodPercent", list.isEmpty() ? BigDecimal.ZERO : BigDecimal.valueOf(goodPingjiaList.size()).divide(BigDecimal.valueOf(list.size()),1, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)));
        // 评价总数
        map.put("pingjiaCount",list.size());
        int count = bsOrderInfoService.count(new LambdaQueryWrapper<BsOrderInfo>().eq(BsOrderInfo::getJingquId, jingquId).eq(BsOrderInfo::getOrderPayStatus, OrderConstants.PAY_STATUS_YES));
        // 购买总数
        map.put("orderCount",count);
        // 好评数量
        map.put("goodPingjiaCount",goodPingjiaList.size());
        long havePictureCount = list.stream().filter(x -> StringUtils.isNotEmpty(x.getPingjiaPictureUrl())).count();
        // 有图数量
        map.put("goodPingjiaCount",havePictureCount);
        return AjaxResult.success(map);
    }


    @ApiOperation("新增评价")
    @PostMapping("save")
    public AjaxResult<?> save(@RequestBody BsPingjia bsPingjia){
        BsOrderInfo orderInfo = bsOrderInfoService.getById(bsPingjia.getOrderId());
        bsPingjia.setJingquId(orderInfo.getJingquId());
        bsPingjia.setUserId(SecurityUtils.getUserId());
        bsPingjia.setPingjiaStatus(PingjiaContants.EXAMINE_WAIT);
        bsPingjiaService.save(bsPingjia);
        //评价完成之后修改订单评价状态
        boolean result = bsOrderInfoService.update(
                new LambdaUpdateWrapper<BsOrderInfo>().eq(BsOrderInfo::getOrderId, orderInfo.getOrderId())
                        .set(BsOrderInfo::getOrderJudgeStatus, OrderConstants.JUDGE_STATUS_YES));
        return toAjax(result);
    }

    @ApiOperation("审核评价")
    @PutMapping("examinePinajia")
    public AjaxResult<?> examinePingjia(@RequestBody BsPingjia bsPingjia){
        BsPingjia entity = bsPingjiaService.getById(bsPingjia.getPingjiaId());
        entity.setPingjiaStatus(bsPingjia.getPingjiaStatus());
        entity.setPingjiaExamineTime(new Date());
        return toAjax(bsPingjiaService.updateById(entity));
    }

    @ApiOperation("删除评价")
    @DeleteMapping("/delete/{pingjiaId}")
    public AjaxResult<?> delete(@PathVariable Long pingjiaId){
        boolean result = bsPingjiaService.removeById(pingjiaId);
        return toAjax(result);
    }




}
